package com.cloudcross.ssp.web.advertiser.main.show;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.support.RequestContextUtils;

import com.cloudcross.ssp.base.web.SimpleController;
import com.cloudcross.ssp.common.utils.Pager;
import com.cloudcross.ssp.model.Account;
import com.cloudcross.ssp.service.IAdvertiserDateService;

@Controller("advertiser.advertiserDataController")
@RequestMapping("/advertiser/main/show/advertiser-data")
public class AdvertiserDataController extends SimpleController {
    @Autowired
    private IAdvertiserDateService advertiserverDateService;

    /**
     * @param model
     * @param request
     * @return
     */
    @RequestMapping
    public String index(Model model, HttpServletRequest request) {

        try {
            LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
            if (localeResolver == null) {
                throw new IllegalStateException("No LocaleResolver found: not in a DispatcherServlet request?");
            }
        } catch (Exception ex) {
        }

        // 得到登录账号
        Account account = getLoginUser();

        model.addAttribute("loginAccountName", account.getAccountName());
        Map<String, Object> paramMap = new HashMap<String, Object>();

        /**
         * 判断一下登录的账号是代理商还是广告主的，如果是广告主则它的代理商id和广告主id不等于0，如果是代理商则代理商的id不等于0广告主id等于
         * 0
         */
        if (0 != account.getAdvertiserId() && 0 != account.getAgentId()) {

            paramMap.put("advertiserId", String.valueOf(account.getAdvertiserId()));

            model.addAttribute("type", "advertiser");
            model.addAttribute("advertiserId", account.getAdvertiserId());
            model.addAttribute("accountId", account.getId());
            model.addAttribute("compareMap", findCompareAjax(paramMap));
        }

        if (0 != account.getAgentId() && 0 == account.getAdvertiserId()) {
            paramMap.put("agentId", String.valueOf(account.getAgentId()));

            model.addAttribute("type", "agent");
            model.addAttribute("agentId", account.getAgentId());
            model.addAttribute("accountId", account.getId());
            model.addAttribute("compareMap", findCompareAjax(paramMap));
        }
        return index;
    }

    @RequestMapping("findCompareAjax")
    protected @ResponseBody Map findCompareAjax(@RequestParam Map<String, Object> paramMap) {
        Long totalImpression = 0l;
        Long totalClick = 0l;
        List<HashMap<String, Object>> list = getchart(paramMap);
        for (int i = 0; i < list.size(); i++) {
            totalImpression = totalImpression + Long.parseLong(list.get(i).get("totalImpression").toString());
            totalClick = totalClick + Long.parseLong(list.get(i).get("totalClick").toString());
        }
        paramMap.put("totalImpression", totalImpression);
        paramMap.put("totalClick", totalClick);
        return paramMap;
    }

    /**
     * 返回图标的数据
     * 
     * @param paramMap
     *            这里面包含了要查询的广告主id，查询的选择的起始时间和截止时间
     *            注意这里的startDate和endDate传递的前端往后端传递的格式为yyyy-MM-dd
     * @return
     */
    @RequestMapping("chart")
    public @ResponseBody List<HashMap<String, Object>> getchart(@RequestParam Map<String, Object> paramMap) {
        Long advertiserId = null;
        Long agentId = null;
        String startDate = null;
        String endDate = null;
        String urlNow;
        String urlPast;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        // 得到登录账号
        Account account = getLoginUser();
        agentId = account.getAgentId();

        /**
         * 对传递过来的数据进行处理,如果传递过来的是一个空值或者空字符串就表示为默认值默认的为全部，值就是-1 时间的默认值为昨天
         */
        if (null == paramMap.get("advertiserId") || "".equals(paramMap.get("advertiserId"))) {
            advertiserId = -1l;
            String advs = advertiserverDateService.findAdvsByAgentId(agentId);
            paramMap.put("adv_id", advs);
        } else {
            advertiserId = Long.parseLong(String.valueOf(paramMap.get("advertiserId")));

            paramMap.put("adv_id", paramMap.get("advertiserId"));
        }

        if (null == paramMap.get("startDate") || "".equals(paramMap.get("startDate"))) {
            startDate = sdf.format(new Date());
            paramMap.put("startDate", startDate);
        } else {
            startDate = String.valueOf(paramMap.get("startDate"));
        }

        if (null == paramMap.get("endDate") || "".equals(paramMap.get("endDate"))) {
            endDate = startDate;
            paramMap.put("endDate", endDate);
        } else {
            endDate = String.valueOf(paramMap.get("endDate"));
        }

        if (paramMap.get("adv_id") != "" && paramMap.get("adv_id") == null) {

            Date date = new Date();

            if (endDate.equals(sdf.format(date))) {

                if (!startDate.equals(endDate)) {
                    // 选择时间为一段时间
                    urlNow = "http://de02.cloudcross.net/scripts/maintenance/dsp_report.php?adv_id=" + paramMap.get("adv_id");
                    // 数据更新插入
                    advertiserverDateService.requestCcData(urlNow);
                    endDate = sdf.format(new Date(date.getTime() - 24 * 60 * 60 * 1000));
                    urlPast = "http://de02.cloudcross.net/scripts/maintenance/dsp_report_history.php?adv_id=" + paramMap.get("adv_id") + "&begin_dt="
                            + startDate + "&end_dt=" + endDate;
                    advertiserverDateService.requestCcData(urlPast);
                } else {
                    // 选择日期为当天
                    urlNow = "http://de02.cloudcross.net/scripts/maintenance/dsp_report.php?adv_id=" + paramMap.get("adv_id");
                    advertiserverDateService.requestCcData(urlNow);
                }
            } else {
                urlPast = "http://de02.cloudcross.net/scripts/maintenance/dsp_report_history.php?adv_id=" + paramMap.get("adv_id") + "&begin_dt="
                        + startDate + "&end_dt=" + endDate;
                advertiserverDateService.requestCcData(urlPast);
            }
        }
        return advertiserverDateService.findChart(startDate, endDate, advertiserId, agentId);
    }

    /**
     * 首页列表模式显示数据
     * 
     * @param model
     * @param paramMap
     *            这里面包含了要查询的广告主id，查询的选择的起始时间和截止时间
     * @param page
     * @return
     */
    @RequestMapping("/list")
    public String list(Model model, @RequestParam HashMap<String, Object> paramMap, @RequestParam(defaultValue = "1") int page) {
        Long advertiserId = null;
        String startDate = null;
        String endDate = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Account account = getLoginUser();
        Long agentId = account.getAgentId();
        /**
         * 对传递过来的数据进行处理,如果传递过来的是一个空值或者空字符串就表示为默认值默认的为全部，值就是-1 时间的默认值为昨天
         */
        if (null == paramMap.get("advertiserId") || "".equals(paramMap.get("advertiserId"))) {
            advertiserId = -1l;
        } else {
            advertiserId = Long.parseLong(String.valueOf(paramMap.get("advertiserId")));
        }

        if (null == paramMap.get("startDate") || "".equals(paramMap.get("startDate"))) {
            startDate = sdf.format(new Date());
        } else {
            startDate = String.valueOf(paramMap.get("startDate"));
        }

        if (null == paramMap.get("endDate") || "".equals(paramMap.get("endDate"))) {
            endDate = startDate;
        } else {
            endDate = String.valueOf(paramMap.get("endDate"));
        }

        int totalRow = 0;
        totalRow = advertiserverDateService.findCountForChart(startDate, endDate, advertiserId, agentId);

        Pager pager = new Pager();
        pager.setPage(page);
        pager.setTotalRow(totalRow);
        List<HashMap<String, Object>> reportList = advertiserverDateService.findChartPage(startDate, endDate, advertiserId, agentId, pager);
        model.addAttribute("pager", pager);
        model.addAttribute("reportList", reportList);
        return page("list");
    }

}
